from django.test import TestCase
from api.views.data_query.utils import (
    get_dates_and_timestamps,
    merge_csv,
    delete_folder,
    zip_dir,
    log_extract,
    trace_extract,
)
from database import log_conn, trace_conn
import os
import pandas as pd


def create_fake_data(path):
    d1 = {"col1": [0, 2, 3, 4, 5], "col2": [1, 2, 3, 4, 5]}
    d2 = {"col1": [0, 2, 3, 4, 5], "col2": [1, 2, 3, 4, 5]}
    os.makedirs(path, exist_ok=True)
    pd.DataFrame(d1).to_csv(os.path.join(path, "d1.csv"))
    pd.DataFrame(d2).to_csv(os.path.join(path, "d2.csv"))
    return [
        os.path.join(path, "d1.csv"),
        os.path.join(path, "d2.csv"),
    ]


class TestDataUtils(TestCase):
    def __init__(self, methodName: str = "runTest") -> None:
        super().__init__(methodName)

    def __del__(self):
        os.system("rm -rf tmp")

    def test_get_dates_and_timestamps_valid(self):
        dates, timestamps = get_dates_and_timestamps(
            **{"start": 1690000000, "end": 1690010000}
        )
        self.assertGreaterEqual(len(dates), 0)
        self.assertGreaterEqual(len(timestamps), 0)

    def test_get_dates_and_timestamps_invalid(self):
        self.skipTest("fail")
        r"""
        fail
        """
        dates, timestamps = get_dates_and_timestamps(
            **{"start": 1690011000, "end": 1690010000}
        )
        self.assertEqual(len(dates), 0)
        self.assertEqual(len(timestamps), 0)

    def test_merge_csv_have_data(self):
        csv_list = create_fake_data("tmp")
        merge_csv("tmp", csv_list, "metric")

    def test_merge_csv_no_data(self):
        self.skipTest("fail")
        r"""
        fail
        """
        create_fake_data("tmp")
        merge_csv("tmp", [], "metric")

    def test_delete_folder(self):
        # exists
        os.mkdir("tmp")
        delete_folder("tmp")

    def test_delete_folder_invalid(self):
        # not exists
        delete_folder("tmp")

    def test_zip(self):
        create_fake_data("tmp/test")
        zip_dir("tmp/test")

    def test_zip_invalid(self):
        self.skipTest("fail")
        r"""
        fail
        """
        zip_dir("tmp/test")

    def test_log_extract(self):
        log_extract(log_conn, 1716739200, 1716739260, "tmp/test")

    def test_log_extract_invalid(self):
        self.skipTest("fail")
        r"""
        fail
        """
        log_extract(log_conn, 1716739270, 1716739260, "tmp/test")

    def test_trace_extract(self):
        trace_extract(trace_conn, 1716739200, 1716739260, "tmp/test")

    def test_trace_extract_invalid(self):
        self.skipTest("fail")
        r"""
        fail
        """
        trace_extract(trace_conn, 1716739270, 1716739260, "tmp/test")
